package com.android.kotlincoroutinemvvmdemo.view

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import com.android.kotlincoroutinemvvmdemo.R
import kotlin.random.Random

class SingleAirBubbleView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : View(context, attributeSet) {

    private var mWidth = 0
    private var mHeight = 0

    private val mPaint by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            style = Paint.Style.FILL
            color = context.resources.getColor(R.color.color_da8989)
        }
    }

    //初始化球半径
    private var mRadius = 10F
    //圆心坐标x
    private var xAir = 0F
    //圆心坐标y
    private var yAir = 0F
    //随机
    private val mRandom = Random(10)

    init {
        setBackgroundColor(resources.getColor(R.color.color_ffcccccc))
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        mWidth = when(MeasureSpec.getMode(widthMeasureSpec)) {
            MeasureSpec.EXACTLY -> {
                MeasureSpec.getSize(widthMeasureSpec)
            }
            else -> {
                context.resources.getDimension(R.dimen.dp_200).toInt()
            }
        } - paddingStart - paddingEnd

        mHeight = when(MeasureSpec.getMode(heightMeasureSpec)) {
            MeasureSpec.EXACTLY -> {
                MeasureSpec.getSize(heightMeasureSpec)
            }
            else -> {
                context.resources.getDimension(R.dimen.dp_200).toInt()
            }
        } - paddingTop - paddingBottom

        setMeasuredDimension(mWidth, mHeight)

        xAir = mWidth / 2.0F
        yAir = mHeight * 1.0F
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.drawCircle(xAir, yAir, mRadius, mPaint)
    }

    private fun setTransport(args: Float) {
        xAir = 200F + (mRandom.nextFloat() - 0.5F) * 2.3F
        mRadius = args * 30F + 10F
        yAir = mHeight.toFloat() - args * mHeight.toFloat() - mRadius * 1.02F
        invalidate()
    }

    fun startAnimation() {
        ObjectAnimator.ofFloat(this, "transport", 0F, 1F).apply {
            repeatMode = ValueAnimator.RESTART
            repeatCount = ValueAnimator.INFINITE
            duration = 8000
            start()
        }
    }

}